package com.canyou.system;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.canyou.api.BaseApiController;
import com.canyou.api.ResponseBO;
import com.canyou.system.entity.dict.ChildDictVO;
import com.canyou.system.entity.dict.DictVO;
import com.canyou.system.entity.dict.ParentDictVO;
import com.canyou.system.model.Dict;
import com.canyou.system.service.DictService;
import com.canyou.utils.StringUtils;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 数据字典 前端控制器
 * </p>
 *
 * @author oyj
 * @since 2021年11月16日
 */
@Api(tags = "字典管理")
@ApiSort(1008)
@RestController
@RequestMapping("/dict")
public class DictController extends BaseApiController {

    @Autowired
    private DictService dictService;

    @ApiOperation("获取字典分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNumber", paramType = "query", value = "当前第几页",
                    dataType = "int", required = false, example = "1"),
            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "每页记录数",
                    dataType = "int", required = false, example = "10"),
            @ApiImplicitParam(name = "name", paramType = "query", value = "字典名称",
                    dataType = "String", required = false),
            @ApiImplicitParam(name = "type", paramType = "query", value = "字典编号",
                    dataType = "String", required = false)
    })
    @GetMapping("/get_parent_page")
    public ResponseBO<IPage<ParentDictVO>> getDictPage(@RequestParam(defaultValue = PAGE_INDEX, required = false) int pageNumber,
                                                       @RequestParam(defaultValue = PAGE_SIZE, required = false) int pageSize,
                                                       @RequestParam(required = false) String name,
                                                       @RequestParam(required = false) String type) {
        IPage<ParentDictVO> page = new Page<>(pageNumber, pageSize);
        return ResponseBO.ok(dictService.getParentPage(page, name, type));
    }

    @ApiOperation(value = "保存字典信息")
    @ApiImplicitParam(name = "parentDictVo", paramType = "body", dataType = "ParentDictVO")
    @PostMapping("/save_parent_dict")
    public ResponseBO saveParentDict(@RequestBody ParentDictVO parentDictVo) {
        String msg = parentDictVo.getId() == null ? "字典新增" : "字典编辑";
        if (StringUtils.isEmpty(parentDictVo.getName())) {
            return ResponseBO.illegal("参数异常，名称不能为空");
        }
        if (StringUtils.isEmpty(parentDictVo.getType())) {
            return ResponseBO.illegal("参数异常，类型不能为空");
        }
        if (!dictService.validDictName(parentDictVo.getId(), parentDictVo.getName())) {
            return ResponseBO.illegal("参数异常，字典名称已存在");
        }
        if (!dictService.validDictType(parentDictVo.getId(), parentDictVo.getType())) {
            return ResponseBO.illegal("参数异常，字典类型已存在");
        }
        Dict dict = new Dict();
        BeanUtils.copyProperties(parentDictVo, dict);
        boolean isSuccess = dictService.saveOrUpdate(dict);
        return ResponseBO.ok(isSuccess, isSuccess ? msg + "成功" : msg + "失败");
    }

    @ApiOperation("获取配置分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNumber", paramType = "query", value = "当前第几页",
                    dataType = "int", required = false, example = "1"),
            @ApiImplicitParam(name = "pageSize", paramType = "query", value = "每页记录数",
                    dataType = "int", required = false, example = "10"),
            @ApiImplicitParam(name = "parentId", paramType = "query", value = "父级id",
                    dataType = "int", required = true),
            @ApiImplicitParam(name = "name", paramType = "query", value = "字典名称",
                    dataType = "String", required = false)
    })
    @GetMapping("/get_child_page")
    public ResponseBO<IPage<ChildDictVO>> getDictConfigPage(@RequestParam(defaultValue = PAGE_INDEX, required = false) int pageNumber,
                                                            @RequestParam(defaultValue = PAGE_SIZE, required = false) int pageSize,
                                                            @RequestParam(required = true) int parentId,
                                                            @RequestParam(required = false) String name) {
        IPage<ChildDictVO> page = new Page<>(pageNumber, pageSize);
        return ResponseBO.ok(dictService.getChildPage(page, name, parentId));
    }

    @ApiOperation(value = "保存配置信息")
    @ApiImplicitParam(name = "childDictVo", paramType = "body", dataType = "ChildDictVO")
    @PostMapping("/save_child_dict")
    public ResponseBO saveChildDict(@RequestBody ChildDictVO childDictVo) {
        String msg = childDictVo.getId() != null ? "字典编辑" : "字典新增";
        if (StringUtils.isEmpty(childDictVo.getName())) {
            return ResponseBO.illegal("参数异常，名称不能为空");
        }
        if (childDictVo.getSort() == null) {
            return ResponseBO.illegal("参数异常，排序值不能为空");
        }
        if (childDictVo.getParentId() == null) {
            return ResponseBO.illegal("参数异常，类型id不能为空");
        }
        Dict dict = dictService.getById(childDictVo.getParentId());
        if (dict == null) {
            return ResponseBO.illegal("参数异常，字典类型不存在");
        }
        if (childDictVo.getId() == null) {
            Integer value = dictService.getDictMaxValue(dict.getType());
            childDictVo.setValue(value + 1);
        }
        if (!dictService.validSortRepeat(childDictVo.getSort(), childDictVo.getId(), dict.getType())) {
            return ResponseBO.illegal("参数异常，排序值已存在");
        }
        if (!dictService.validDictValue(childDictVo.getValue(), childDictVo.getId(), dict.getType())) {
            return ResponseBO.illegal("参数异常，字典值已存在");
        }
        Dict childDict = new Dict();
        childDict.setId(childDictVo.getId());
        childDict.setValue(childDictVo.getValue());
        childDict.setName(childDictVo.getName());
        childDict.setSort(childDictVo.getSort());
        childDict.setRemark(childDictVo.getRemark());
        childDict.setParentId(dict.getId());
        childDict.setType(dict.getType());
        boolean isSuccess = dictService.saveOrUpdate(childDict);
        return ResponseBO.ok(isSuccess, isSuccess ? msg + "成功" : msg + "失败");
    }

    @ApiOperation(value = "获取字典详情")
    @ApiImplicitParam(name = "id", paramType = "query", value = "字典id", dataType = "Long", required = true)
    @GetMapping("/get_dict_info")
    public ResponseBO<Dict> getDictInfo(Long id) {
        return ResponseBO.ok(dictService.getById(id));
    }

    @ApiOperation("删除字典信息")
    @ApiImplicitParam(name = "id", paramType = "body", value = "字典配置项id", dataType = "Long", required = true)
    @PostMapping("/delete")
    public ResponseBO deleteById(@RequestBody Long id) {
        return ResponseBO.ok(dictService.removeById(id) ? "删除成功" : "删除失败");
    }

    @ApiOperation(value = "根据字典类型获取字典数组")
    @ApiImplicitParam(name = "type", paramType = "query", value = "字典类型", dataType = "String", required = true)
    @GetMapping("/get_dict_list")
    public ResponseBO<List<DictVO>> getDictList(@RequestParam String type) {
        if (StringUtils.isEmpty(type)) {
            return ResponseBO.illegal("字典类型为空");
        }
        List<DictVO> list = dictService.getDictList(type);
        return ResponseBO.ok(list);
    }
}
